<?php

namespace App\Admin\Controllers;

use App\Http\Controllers\BaseController;
use App\Models\AgentUser;
use App\Models\GoodOrder;
use App\Models\GoodOrderDetail;
use App\Models\PaymentOrder;
use App\Models\ServiceOrder;
use App\Models\ShopUser;
use App\Models\User;
use App\Models\Worker;
use Dcat\Admin\Layout\Content;
use Dcat\Admin\Layout\Row;
use Dcat\Admin\Widgets\Tab;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;

class BasicController extends BaseController
{
    public function index(Content $content)
    {
        return $content
            ->translation($this->translation())
            ->title("数据看板")
            ->body(function (Row $row){
                $tab = Tab::make();
                $carbon = now()->startOfMonth();
                $days = $carbon->daysInMonth;
                $values = [];
                $dates = [];
                for ($i=1;$i<=$days;$i++){
                    $range[0] = $carbon->startOfDay()->format("Y-m-d 00:00:00");
                    $range[1] = $carbon->endOfDay()->format("Y-m-d 23:59:59");
                    $carbon = Carbon::parse($range[0])->addDay();
                    $dates[] = Carbon::parse($range[0])->format("m月d日");
                    $values[0][] = GoodOrder::query()->whereIn("state",[1,2,3,4])->whereBetween("created_at",$range)->count();
                    $values[1][] = ServiceOrder::query()->where("status","<>",4)->whereBetween("created_at",$range)->count();
                    $values[2][] = PaymentOrder::query()->where("pay_status",2)->whereBetween("created_at",$range)->count();
                }
                $data['dates'] = $dates;
                $data['series'] = [
                    ['name'=>'商城交易量',"type"=>"line",'data'=>$values[0]],
                    ['name'=>'洗车服务交易量',"type"=>"line",'data'=>$values[1]],
                    ['name'=>'会员卡交易量',"type"=>"line",'data'=>$values[1]],
                ];
                $tab->add('基础数据', view('admin.basic.index',$data), true);
                $row->column(12,$tab->withCard());
            });
    }

    protected function getWhereRange($field = "created_at"): \Closure
    {
        return function ($query) use ($field) {
            $type = request()->post('type');
            $range = request()->post('range');
            if ($type=='custom'){
                $query->when($range,function ($q,$value){
                    $value[0] = Carbon::parse($value[0]/1000)->format("Y-m-d 00:00:00");
                    $value[1] = Carbon::parse($value[1]/1000)->format("Y-m-d 23:59:59");
                    $q->whereBetween("created_at",$value);
                });
            }else{
                $carbon = now();
                switch ($type){
                    case "yesterday":
                        $d = $carbon->addDays(-1);
                        $range[0] = $d->startOfDay()->format("Y-m-d 00:00:00");
                        $range[1] = $d->endOfDay()->format("Y-m-d 23:59:59");
                        break;
                    case "today":
                        $range[0] = $carbon->startOfDay()->format("Y-m-d 00:00:00");
                        $range[1] = $carbon->endOfDay()->format("Y-m-d 23:59:59");
                        break;
                    case "week":
                        $range[0] = $carbon->startOfWeek()->format("Y-m-d 00:00:00");
                        $range[1] = $carbon->endOfWeek()->format("Y-m-d 23:59:59");
                        break;
                    case "month":
                        $range[0] = $carbon->startOfMonth()->format("Y-m-d 00:00:00");
                        $range[1] = $carbon->endOfMonth()->format("Y-m-d 23:59:59");
                        break;
                    case "quarter":
                        $range[0] = $carbon->startOfQuarter()->format("Y-m-d 00:00:00");
                        $range[1] = $carbon->endOfQuarter()->format("Y-m-d 23:59:59");
                        break;
                    case "year":
                        $range[0] = $carbon->startOfYear()->format("Y-m-d 00:00:00");
                        $range[1] = $carbon->endOfYear()->format("Y-m-d 23:59:59");
                        break;
                    default:
                        $range = [];
                        break;
                }
                if ($range){
                    $query->whereBetween($field,$range);
                }
            }
        };
    }

    protected function range()
    {
        $whereRange = $this->getWhereRange();
        $data['items'] = [

            ['label'=>'洗车交易量','value'=>ServiceOrder::query()->where($whereRange)->where("status","<>",4)->count()],
            ['label'=>'洗车交易额','value'=>ServiceOrder::query()->where($whereRange)->where("status","<>",4)->sum("amount")],
            ['label'=>'商城交易量','value'=>GoodOrder::query()->where($whereRange)->whereIn("state",[1,2,3,4])->count()],
            ['label'=>'商城交易额','value'=>GoodOrder::query()->where($whereRange)->whereIn("state",[1,2,3,4])->sum("amount")],
            ['label'=>'会员卡交易量','value'=>PaymentOrder::query()->where("type",3)->where($whereRange)->where("pay_status",1)->count()],
            ['label'=>'会员卡交易额','value'=>PaymentOrder::query()->where("type",3)->where($whereRange)->where("pay_status",1)->sum("amount")],
            ['label'=>'总用户量','value'=>User::query()->whereNotNull("nickname")->where($whereRange)->count()],
            ['label'=>'总门店量','value'=>ShopUser::query()->where($whereRange)->count()],
            ['label'=>'总洗车工量','value'=>Worker::query()->where($whereRange)->count()],
            ['label'=>'总代理量','value'=>AgentUser::query()->where($whereRange)->count()],
            ['label'=>'充值余额','value'=>PaymentOrder::query()->where("type",0)->where("pay_status",1)->where($whereRange)->sum("amount")],
        ];
        $selectFields1 = ["good_order_details.id as g_id","good_order_details.good_id as good_id","good_order_details.good_name as good_name"];
        $selectFields2 = ["service_orders.id as s_id","service_orders.shop_id as shop_id","shop_users.name as shop_name"];
        $goods = GoodOrderDetail::query()->select($selectFields1)->addSelect(DB::raw("sum(good_order_details.good_price) as good_num"))->join("good_orders","good_orders.order_no","=","good_order_details.oid")->where($this->getWhereRange("good_order_details.created_at"))->whereIn("good_orders.state",[1,2,3,4])->groupBy("good_order_details.good_id")->orderByDesc("good_num")->limit(20)->get()->toArray();
        $services = ServiceOrder::query()->select($selectFields2)->addSelect(DB::raw("sum(service_orders.amount) as shop_num"))->join("shop_users","shop_users.id","=","service_orders.shop_id")->where($this->getWhereRange("service_orders.created_at"))->where("service_orders.status","<>",4)->groupBy("service_orders.shop_id")->orderByDesc("shop_num")->limit(20)->get()->toArray();
        $ranks = [];
        foreach ($goods as $key=>$good){
            $good['good_name'] = "【商品ID:{$good["good_id"]}】".$good['good_name'];
            $ranks[$key] = $good;
            if (isset($services[$key])){
                $ranks[$key] = array_merge($good,$services[$key]);
            }
        }
        foreach ($services as $key=>$service){
            if (isset($goods[$key])){
                $goods[$key]['good_name'] = "【商品ID:{$goods[$key]["good_id"]}】".$goods[$key]['good_name'];
                $ranks[$key] = array_merge($service,$goods[$key]);
            }else{
                $ranks[$key] = $service;
            }
        }
        $data['ranks'] = $ranks;
        return $this->response()->data($data);
    }




}
